import asyncio
import config
import os
from downloader import Downloader, Album, Track
from pathlib import Path
from utils import download_image, move, parse_json, add_zeros


async def main(download: Album | Track):
    if not config.tmp_folder.exists():
        config.tmp_folder.mkdir()
    music_folder = Path(config.music_folder)

    album, tracks = await Downloader.download(download)
    if album is None:
        for path, track in tracks.items():
            track_title = config.track_filename_template.format(
                artist=track.artist,
                title=track.title,
                number=" "
            ).strip()
            await move(path, music_folder / track_title)
    else:
        album_folder_name = config.playlist_folder_template.format(
            artist=album.artist,
            title=album.title
        )
        album_folder = music_folder / album_folder_name
        if not album_folder.is_dir():
            album_folder.mkdir()

        tracks_count = len(str(len(tracks)))
        for path, track in tracks.items():
            track_title = config.track_filename_template.format(
                artist=track.artist,
                title=track.title,
                number=add_zeros(track.number, tracks_count)
            )
            await move(path, album_folder / track_title)

        cover = await download_image(album.cover)
        extension = str(cover).split(".")[-1]
        await move(cover, album_folder / ("cover." + extension))

        os.system(f'explorer "{album_folder}"')
        return album_folder


if __name__ == "__main__":
    with open("download.json", "r", encoding="utf-8") as f:
        download = parse_json(f.read())
    asyncio.run(main(download))
